<template>
  <div class="base-info-box">
    <el-row :gutter="20">
      <el-col :span="17">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基础设置</span>
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button type="primary" link>
                    <el-icon><Setting /></el-icon>
                  </el-button>
                </template>
                <div class="setting-popover">
                  <div class="setting-title">显示项设置</div>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange" size="small">全选</el-checkbox>
                  <el-checkbox-group v-model="visibleFields" @change="handleCheckedChange">
                    <el-checkbox v-for="field in fieldSettings" :key="field.prop" :label="field.prop" size="small">
                      {{ field.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-popover>
            </div>
          </template>

          <el-form ref="formRef" :model="formData" label-position="top" :inline="true" class="base-form">
            <el-form-item v-show="visibleFields.includes('name')" label="站点名称" prop="name">
              <template v-if="editingField !== 'name'">
                <span class="editable-text" @click="startEdit('name')">
                  <span class="text-content">{{ formData.name || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.name" @blur="finishEdit('name')" v-focus placeholder="输入站点名称" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('domain')" label="静态域名" prop="domain">
              <template v-if="editingField !== 'domain'">
                <span class="editable-text" @click="startEdit('domain')">
                  <span class="text-content">{{ formData.domain || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.domain" @blur="finishEdit('domain')" v-focus placeholder="输入静态域名" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('uri')" label="URI" prop="uri">
              <template v-if="editingField !== 'uri'">
                <span class="editable-text" @click="startEdit('uri')">
                  <span class="text-content">{{ formData.uri || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.uri" @blur="finishEdit('uri')" v-focus placeholder="输入URI" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('title')" label="站点标题" prop="title">
              <template v-if="editingField !== 'title'">
                <span class="editable-text" @click="startEdit('title')">
                  <span class="text-content">{{ formData.title || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.title" @blur="finishEdit('title')" v-focus placeholder="输入站点标题" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('description')" label="站点描述" prop="description">
              <template v-if="editingField !== 'description'">
                <span class="editable-text" @click="startEdit('description')">
                  <span class="text-content">{{ formData.description || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.description" type="textarea" autosize @blur="finishEdit('description')" v-focus placeholder="输入站点描述" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('keywords')" label="关键字" prop="keywords">
              <template v-if="editingField !== 'keywords'">
                <span class="editable-text" @click="startEdit('keywords')">
                  <span class="text-content">{{ formData.keywords || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.keywords" type="textarea" autosize @blur="finishEdit('keywords')" v-focus placeholder="输入关键字" />
            </el-form-item>
            
            <el-form-item v-show="visibleFields.includes('logo')" label="站点图标" prop="logo">
              <div v-if="editingField !== 'logo'">
                <span class="editable-text" @click="startEdit('logo')">
                  <img class="text-content" :src="formData.logo" alt="" />
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </div>
              <div v-else>
                <img class="text-content" :src="formData.logo" alt="" />
              </div>
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('themeColor')" label="主题色" prop="themeColor">
              <el-color-picker v-model="formData.themeColor" @change="handleThemeColorChange" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('setting.statisticId')" label="百度统计ID" prop="setting.statisticId">
              <template v-if="editingField !== 'setting.statisticId'">
                <span class="editable-text" @click="startEdit('setting.statisticId')">
                  <span class="text-content">{{ formData.setting?.statisticId || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.setting.statisticId" @blur="finishEdit('setting.statisticId')" v-focus placeholder="输入百度统计ID" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('setting.maxWidth')" label="图片最大宽度" prop="setting.maxWidth">
              <template v-if="editingField !== 'setting.maxWidth'">
                <span class="editable-text" @click="startEdit('setting.maxWidth')">
                  <span class="text-content">{{ formData.setting?.maxWidth || '-' }}px</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input-number v-else v-model="formData.setting.maxWidth" @blur="finishEdit('setting.maxWidth')" v-focus :min="0" placeholder="输入图片最大宽度" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('setting.maxSize')" label="视频最大体积" prop="setting.maxSize">
              <template v-if="editingField !== 'setting.maxSize'">
                <span class="editable-text" @click="startEdit('setting.maxSize')">
                  <span class="text-content">{{ formData.setting?.maxSize || '-' }}MB</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input-number v-else v-model="formData.setting.maxSize" @blur="finishEdit('setting.maxSize')" v-focus :min="0" placeholder="输入视频最大体积" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('setting.ext')" label="允许视频格式" prop="setting.ext">
              <template v-if="editingField !== 'setting.ext'">
                <span class="editable-text" @click="startEdit('setting.ext')">
                  <span class="text-content">{{ formatExtensions(formData.setting?.ext) || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.setting.ext" type="textarea" autosize @blur="finishEdit('setting.ext')" v-focus placeholder="输入允许上传的视频格式，多种格式用 | 分割" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="7">
        <el-card>
          <template #header>
            <h3>事件与提醒</h3>
          </template>
          <el-empty description="暂无数据"></el-empty>
        </el-card>
      </el-col>
    </el-row>
    <ImageUpload v-model:showDialog="showImgUpload" allow=".ico" :limit="1" @getImage="getImage"></ImageUpload>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Setting } from '@element-plus/icons-vue'
import { updateSite } from '@/api/site'

const props = defineProps({
  form: {
    type: Object,
    required: true
  }
})
const emits = defineEmits(['update'])
const formData = ref({ ...props.form })
watch(
  () => props.form,
  newVal => {
    formData.value = { ...newVal }
  },
  { deep: true }
)

// 显示控制相关
const fieldSettings = [
  { prop: 'name', label: '站点名称' },
  { prop: 'domain', label: '静态域名' },
  { prop: 'uri', label: 'URI' },
  { prop: 'title', label: '站点标题' },
  { prop: 'description', label: '站点描述' },
  { prop: 'keywords', label: '关键字' },
  { prop: 'themeColor', label: '主题色' },
  { prop: 'setting.statisticId', label: '百度统计ID' },
  { prop: 'setting.maxWidth', label: '图片最大宽度' },
  { prop: 'setting.maxSize', label: '视频最大体积' },
  { prop: 'setting.ext', label: '允许视频格式' },
  { prop: 'logo', label: '站点图标' }
]

const visibleFields = ref(fieldSettings.map(field => field.prop))
const checkAll = ref(true) // 是否全选
const isIndeterminate = ref(false) // 是否半选

const handleCheckAllChange = (val) => {
  visibleFields.value = val ? fieldSettings.map(field => field.prop) : []
  isIndeterminate.value = false
}

const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === fieldSettings.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < fieldSettings.length
}

// 格式化允许上传的视频格式
const formatExtensions = ext => {
  if (!ext) return ''
  const exts = ext.split('|')
  if (exts.length <= 3) return ext
  return `${exts.slice(0, 3).join('|')} 等${exts.length}种格式`
}

// 自定义 v-focus 指令
const vFocus = {
  mounted: el => {
    const input = el.querySelector('input') || el.querySelector('textarea')
    if (input) {
      input.focus()
    }
  }
}

const editingField = ref('')
const originalValue = ref(null)
const startEdit = field => {
  editingField.value = field
  // 保存原始值
  if (field.includes('.')) {
    // 处理嵌套属性
    const [parent, child] = field.split('.')
    originalValue.value = formData.value[parent]?.[child]
  } else {
    originalValue.value = formData.value[field]
  }
  if (field === 'logo') {
    showImgUpload.value = true
  }
}

const finishEdit = async field => {
  let currentValue
  if (field.includes('.')) {
    // 处理嵌套属性
    const [parent, child] = field.split('.')
    currentValue = formData.value[parent]?.[child]
  } else {
    currentValue = formData.value[field]
  }

  // 检查值是否发生变化
  if (currentValue !== originalValue.value) {
    const res = await updateSite(formData.value)
    if (res.code === 20000) {
      ElMessage.success('更新成功')
      emits('update')
    }
  }
  
  editingField.value = ''
  originalValue.value = null
}

const handleThemeColorChange = async () => {
  const res = await updateSite(formData.value)
  if (res.code === 20000) {
    ElMessage.success('更新成功')
    emits('update')
  }
}

// logo上传
const showImgUpload = ref(false)
const getImage = data => {
  formData.value.logo = data[0].url
}
watch(showImgUpload, val => {
  if (!val) {
    finishEdit('logo')
  }
})
</script>

<style lang="scss" scoped>
.base-info-box {
  .base-form {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;

    :deep(.el-form-item) {
      margin-bottom: 0;
      width: 100%;

      &.is-required .el-form-item__label:before {
        display: none;
      }
    }
  }

  .editable-text {
    display: inline-flex;
    align-items: center;
    border-radius: 4px;
    cursor: pointer;

    .text-content {
      max-width: 90%;
      margin-right: 10px;
      font-size: 12px;
      @include textEllipsis(24px, 1);
    }

    &:hover {
      background-color: #f5f7fa;

      .edit-icon {
        opacity: 1;
      }
    }

    .edit-icon {
      font-size: 12px;
      opacity: 0;
      transition: opacity 0.2s;
      color: $mainColor;
    }
  }

  :deep(.el-textarea__inner) {
    font-family: inherit;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .setting-popover {
    .setting-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 12px;
    }

    :deep(.el-checkbox-group) {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    :deep(.el-divider--horizontal) {
      margin: 12px 0;
    }
  }
}
</style>
